package org.csu.mypetstore.controller;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Category;
import org.csu.mypetstore.domain.Item;
import org.csu.mypetstore.domain.Product;
import org.csu.mypetstore.service.CatalogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Controller
@RequestMapping("/catalog")
@SessionAttributes("loginAccount")
public class CatalogController {

    @Autowired
    private CatalogService catalogService;

    @GetMapping("/main")
    public String viewMain(){
        return "/catalog/Main";
    }

    @GetMapping("/viewCategory")
    public String viewCategory(String categoryId, Model model){

        if (categoryId != null) {

            List<Product> productList = catalogService.getProductListByCategory(categoryId);
            Category category = catalogService.getCategory(categoryId);

            model.addAttribute("category",category);
            model.addAttribute("productList",productList);

            return "/catalog/Category";
        }

        return "/catalog/Main";
    }

    @GetMapping("/viewProduct")
    public String viewProduct(String productId,Model model){

        if (productId != null) {
            List<Item> itemList = catalogService.getItemListByProduct(productId);
            Product product = catalogService.getProduct(productId);
            model.addAttribute("itemList",itemList);
            model.addAttribute("product",product);
            return "/catalog/Product";
        }

        return "/catalog/Category";
    }

    @GetMapping("/viewItem")
    public String viewItem(String itemId,Model model){

        Item item = catalogService.getItem(itemId);
        Product product = item.getProduct();
        model.addAttribute("item",item);
        model.addAttribute("product",product);

        return "/catalog/Item";
    }

    @GetMapping("/viewCategoryInMain")
    @ResponseBody
    private String viewCategoryInMain(String categoryId){
        //根据这个查这个类别
        Category category = catalogService.getCategory(categoryId);
        List<Product> productList = catalogService.getProductListByCategory(categoryId);

        String str = "";
        str += categoryId + ",";

        for(int i = 0;i < productList.size();i++){
            if(i < productList.size()-1) {
                str += productList.get(i).getProductId()+",";
                str += productList.get(i).getName() + ",";
            }
            else{
                str += productList.get(i).getProductId()+",";
                str += productList.get(i).getName();
            }
        }
        return str;
    }

    @GetMapping("/searchCompletion")
    @ResponseBody
    private String searchCompletion(String keyword){

        List<Product> productList = catalogService.searchProductList(keyword);

        String str = "";

        for(int i = 0;i < productList.size();i++){
            if(i < productList.size() - 1)
                str += productList.get(i).getName() + ",";
            else
                str += productList.get(i).getName();
        }
        return str;
    }

    @PostMapping("/search")
    private String search(String keyword,Model model){
        List<Product> productList = catalogService.searchProductList(keyword);

        model.addAttribute("productList",productList);

        return "/catalog/SearchProducts";
    }

    @GetMapping("/addProduct")
    private String addProduct(){
        return "/administrator/catalog/Addproduct";
    }

    @GetMapping("/addItem")
    private String addItem(){
        return "/administrator/catalog/AddItem";
    }

    @GetMapping("/createProductId")
    @ResponseBody
    private String createProductId(String categoryId){
        String a = "";

        //生成前缀
        if(categoryId.equals("BIRDS"))
            a += "AV-";
        else if(categoryId.equals("FISH"))
            a += "Fl-";
        else if(categoryId.equals("CATS"))
            a += "FL-";
        else if(categoryId.equals("DOGS"))
            a += "K9-";
        else if(categoryId.equals("REPTILES"))
            a += "RP-";

        boolean exist = true;
        String str = "";

        while(exist){
            str = a;
            //随机生成字符串
            str += getRandomString("ABCDEFGHIJKOMQOPQRSTUVWXYZ0123456789") + '-';
            str += getRandomString("0123456789");

            exist = catalogService.checkProductId(str);
        }

        return str;
    }

    private String getRandomString(String str) {
        Random random=new Random();
        StringBuffer s =new StringBuffer();
        for(int i = 0;i < 2;i++){
            int number=random.nextInt(str.length());
            s.append(str.charAt(number));
        }
        return s.toString();
    }

    @PostMapping("/saveProduct")
    private String saveProduct(Product product, @RequestParam("upload")MultipartFile upload) throws IOException {

        String fileName = upload.getOriginalFilename();
        // 获取文件后缀
        String prefix=fileName.substring(fileName.lastIndexOf("."));
        // 用uuid作为文件名，防止生成的临时文件重复
        final File excelFile = File.createTempFile("imagesFile-"+System.currentTimeMillis(), prefix);
        // 将MultipartFile转为File
        upload.transferTo(excelFile);

        //调用腾讯云工具上传文件
        String fileName1 = TencentCOS.uploadfile(excelFile,product.getProductId());
        System.out.println(fileName1);
        String str = "https://csu-515-1305437015.cos.ap-guangzhou.myqcloud.com/";
        str += fileName1;

        product.setImages(str);
        //程序结束时，删除临时文件
        deleteFile(excelFile);
        //存入图片名称，用于网页显示

        //保存到数据库中
        catalogService.insertProduct(product);

        //在填写完信息之后直接返回到填写信息界面
        return "/administrator/catalog/AddItem";
    }
    private void deleteFile(File... files) {
        for (File file : files) {
            if (file.exists()) {
                file.delete();
            }
        }
    }

    //这是在点击AddItem之后选择好Category之后利用JS生成ProductId下拉列表
    @GetMapping("/getProductIdList")
    @ResponseBody
    private String getProductIdList(String categoryId){

        List<Product> productIdArrayList = catalogService.getProductListByCategory(categoryId);
        String str = "";

        for(Product list:productIdArrayList){
            str += list.getProductId() + ",";
        }

        int amountItem = catalogService.getItemAmount();
        String ItemId = "EST-"+(amountItem+1);
        str += ItemId;
        return str;
    }

    //这是add完之后执行的
    @GetMapping("/saveItem")
    private String saveItem(Item item){

        catalogService.insertItem(item);
        catalogService.insertInven(item.getItemId(),item.getSupplierId());

        //在填写完信息之后直接返回到填写信息界面

        return "redirect:/catalog/AdminViewItem";
    }

    @GetMapping("/deleteProduct")
    private String deleteProduct(String productId,Model model){
        Product product = catalogService.getProduct(productId);

        if(product == null){
            model.addAttribute("error","该产品已经被删除");
            return "/administrator/ErrorH";
        }else{
            catalogService.deleteProduct(productId);
            catalogService.deleteItemList(productId);
        }

        return "/administrator/catalog/ViewProduct";
    }

    @GetMapping("/deleteItem")
    private String deleteItem(String itemId,Model model){
        Item item = catalogService.getItem(itemId);

        if(item == null){
            model.addAttribute("error","该产品已经被删除");
            return "/ErrorH";
        }else{
            catalogService.deleteItem(itemId);
            catalogService.deleteInVen(itemId);
        }

        return "redirect:/catalog/AdminViewItem";
    }

    @GetMapping("/editItem")
    private String editItem(Model model,String itemId){

        Item item = catalogService.getItem(itemId);
        model.addAttribute("item",item);

        return "/administrator/catalog/EditItem";
    }

    //这是在更新完之后执行的servlet
    @GetMapping("/updateProduct")
    private String updateProduct(Product product){

        catalogService.updateProduct(product);
        return "/administrator/catalog/main";
    }

    @PostMapping("/updateItem")
    private String updateItem(Item item,MultipartFile upload) throws IOException {

        if(upload != null){

            String fileName = upload.getOriginalFilename();
            // 获取文件后缀
            String prefix=fileName.substring(fileName.lastIndexOf("."));
            // 用uuid作为文件名，防止生成的临时文件重复
            final File excelFile = File.createTempFile("imagesFile-"+System.currentTimeMillis(), prefix);
            // 将MultipartFile转为File
            upload.transferTo(excelFile);

            //调用腾讯云工具上传文件
            String fileName1 = TencentCOS.uploadfile(excelFile,item.getProductId());

            String str = "https://csu-515-1305437015.cos.ap-guangzhou.myqcloud.com/";
            str += fileName1;

            Product product = catalogService.getProduct(item.getProductId());

            product.setImages(str);

            //程序结束时，删除临时文件
            deleteFile(excelFile);
            //存入图片名称，用于网页显示

            catalogService.updateProduct(product);
        }

        catalogService.updateItem(item);
        return "redirect:/catalog/AdminViewItem";
    }

    @GetMapping("/AdminViewItem")
    private String AdminViewItem(Model model){
        ArrayList<Item> AdminitemList = catalogService.getItemList();

        model.addAttribute("AdminitemList",AdminitemList);
        return "/administrator/catalog/viewItem";
    }

    @GetMapping("/AdminViewMain")
    private String AdminViewMain(){
        return "/administrator/catalog/main";
    }

    @GetMapping("/AdminSignonForm")
    private String AdminSignonForm(){
        return "/administrator/account/SignonForm";
    }

}
